<template>
  <div class="cu-common-layout crmcustomer">
    <div class="cu-common-layout-center">
      <el-form @submit.native.prevent size="mini" label-position="right" class="cu-common-search-box">
        <el-row :gutter="15">
          <el-col :span="6">
            <el-form-item label="所在区域" prop="area">
              <custom-address v-model="query.area" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户信息" prop="info">
              <el-input v-model="query.info" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户类别" prop="category">
              <custom-tree-select
                v-model="query.category"
                :options="categoryOptions"
                placeholder="请选择"
                lastLevel
                clearable
                required
                :props="{
                  value: 'enCode', // ID字段名
                  label: 'fullName', // 显示名称
                  children: 'children', // 子级字段名
                  disabled: 'selectable'
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="咨询时间" prop="consultTime">
              <el-date-picker v-model="query.consultTime" type="daterange" value-format="timestamp" format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="6">
            <el-form-item label="咨询渠道" prop="channel">
              <el-select v-model="query.channel" clearable required :style="{ width: '100%' }" filterable>
                <el-option-group v-for="group in channelOptions" :key="group.id" :label="group.fullName">
                  <el-option v-for="item in group.children" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="招商经理" prop="managerId">
              <el-select v-model="query.managerId" filterable>
                <el-option :key="item.id" :label="item.realName" :value="item.id" v-for="item in userList" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="query.status" filterable>
                <el-option :key="0" label="未分配" :value="0" />
                <el-option :key="1" label="已分配" :value="1" />
                <el-option :key="2" label="已退回" :value="2" />
                <el-option :key="3" label="重点客户" :value="3" />
                <el-option :key="4" label="定金客户" :value="4" />
                <el-option :key="5" label="成交客户" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <template v-if="showAll">

          </template> -->
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">
                {{ $t('common.reset') }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div class="left-btn">
            <top-opts @add="addOrUpdateHandle()" :disabled="isdisabled">
              <el-button v-has="'btn_assign'" type="primary" icon="el-icon-s-promotion" :disabled="isdisabled" @click="assignHandle()">
                批量分配
              </el-button>
            </top-opts>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list" :hasC="true" @selection-change="handleSelectionChange">
          <el-table-column prop="managerName" label="跟进人" align="left" v-if="custom.hasP('managerName')" width="80" />
          <el-table-column prop="name" label="咨询人" align="left" v-if="custom.hasP('name')" width="100" show-overflow-tooltip></el-table-column>
          <el-table-column label="联系方式" width="120" v-if="custom.hasP('mobile')" align="left">
            <template slot-scope="scope">
              <span>
                <i v-if="scope.row.mobile != null" class="ym-custom ym-custom-cellphone"></i>
                {{ scope.row.mobile }}
              </span>
              <span>
                <i v-if="scope.row.wechat != null" class="ym-custom ym-custom-wechat"></i>
                {{ scope.row.wechat }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="province" label="省份" align="left" v-if="custom.hasP('province')" width="100" show-overflow-tooltip />
          <el-table-column prop="city" label="城市" align="left" v-if="custom.hasP('province')" width="100" show-overflow-tooltip />
          <el-table-column prop="category" label="客户类别" align="left" v-if="custom.hasP('category')" width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.category | dynamicTreeCodeText(categoryOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="receiveTime" label="分配时间" align="center" v-if="custom.hasP('receiveTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <el-table-column prop="lastConsultTime" label="最新咨询时间" align="left" v-if="custom.hasP('lastConsultTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <el-table-column prop="channel" label="咨询渠道" align="left" v-if="custom.hasP('channel')" width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.channel | dynamicTreeCodeText(channelOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastTrack" label="最近跟进" align="left" v-if="custom.hasP('lastTrack')" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" align="center" v-if="custom.hasP('status')" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 1" style="color:#67C23A">
                已分配
              </span>
              <span v-else-if="scope.row.status == 2" style="color:#909399">
                已退回
              </span>
              <span v-else-if="scope.row.status == 3" style="color:#E6A23C">
                重点客户
              </span>
              <span v-else-if="scope.row.status == 4" style="color:#409EFF">
                定金客户
              </span>
              <span v-else-if="scope.row.status == 5" style="color:#000000">
                签约客户
              </span>
              <span v-else style="color:#F56C6C">
                未分配
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="录入时间" align="center" v-if="custom.hasP('createTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <el-table-column prop="createUserName" label="录入人员" align="left" v-if="custom.hasP('createUserName')" width="100" show-overflow-tooltip />
          <el-table-column label="操作" fixed="right" width="120" align="center">
            <template slot-scope="scope">
              <table-opts @edit="addOrUpdateHandle(scope.row.id)" @del="handleDel(scope.row.id)">
                <el-button type="text" size="mini" @click="addSubFormHandle(scope.row.id)">动态</el-button>
              </table-opts>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <custom-form v-if="formVisible" ref="CustomForm" @refresh="search" />
    <track-form v-if="trackFormVisible" ref="TrackForm" @refresh="initData" />
    <assign-form v-if="assignFormVisible" ref="AssignForm" @refresh="initData" />
  </div>
</template>
<script>
import CustomForm from './Form'
import AssignForm from '../components/AssignForm'
import TrackForm from '../components/TrackForm'
import request from '@/utils/request'
export default {
  name: 'assgin',
  components: {
    CustomForm,
    AssignForm,
    TrackForm
  },
  data() {
    return {
      showAll: false,
      isdisabled: false,
      query: {
        name: undefined,
        area: undefined,
        info: undefined,
        category: undefined,
        consultTime: undefined,
        channel: undefined,
        managerId: undefined,
        status: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'lastConsultTime'
      },
      formVisible: false,
      assignFormVisible: false,
      trackFormVisible: false,
      channelOptions: [],
      genderOptions: [],
      userList: [],
      categoryOptions: []
    }
  },
  computed: {},
  created() {
    this.getChannelOptions()
    this.getGenderOptions()
    this.getCategoryOptions()
    this.getUserList()
    this.initData()
  },
  methods: {
    getUserList() {
      this.$store.dispatch('base/getUserList').then(res => {
        this.userList = res.filter(o => o.enabledMark == 1 && o.positionId.indexOf('445842201948194053') > -1)
      })
    },
    getChannelOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'ConsultChannels' }).then(res => {
        this.channelOptions = res
      })
    },
    getCategoryOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'CustomerCategory' }).then(res => {
        this.categoryOptions = res
      })
    },
    getGenderOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'sex' }).then(res => {
        this.genderOptions = res
      })
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: '/api/crm/allocation',
        method: 'GET',
        data: query
      })
        .then(res => {
          this.list = res.data.list
          this.total = res.data.pagination.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },

    handleSelectionChange(val) {
      this.multipleSelection = this.reduceSame(val)
    },
    // 数组对象去重
    reduceSame(arr) {
      let obj = {}
      return arr.reduce(function(prev, item) {
        obj[item.id] ? '' : (obj[item.id] = 1 && prev.push(item))
        return prev
      }, [])
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/crm/allocation/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    assignHandle() {
      if (this.multipleSelection.length > 0) {
        this.assignFormVisible = true
        this.$nextTick(() => {
          this.$refs.AssignForm.init(this.multipleSelection)
        })
      }
    },

    addSubFormHandle(id) {
      this.trackFormVisible = true
      this.$nextTick(() => {
        this.$refs.TrackForm.init(id)
      })
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'lastConsultTime'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        if (key != 'status') this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'lastConsultTime'
      }
      this.initData()
    }
  }
}
</script>
<style lang="scss" scoped>
.crmcustomer {
  .cu-common-layout-main {
    padding: 0;
    .customerTabs {
      height: 100%;
    }
    .line1 {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
    }
  }
}
</style>
